﻿/* 
 * Copyright (c) Intel Corporation
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * -- Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * -- Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * -- Neither the name of the Intel Corporation nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE INTEL OR ITS
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Web;
using DotNetOpenAuth;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.OAuth.Messages;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.ChannelElements;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using ExtensionLoader;
using ExtensionLoader.Config;
using HttpServer;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.Http;
using OpenMetaverse.StructuredData;
using CableBeachMessages;
using OAuthConsumer = DotNetOpenAuth.OAuth.WebConsumer;

namespace WorldServer.Extensions
{
    public class RexOpenIDLogin : OpenIDLogin
    {

        public RexOpenIDLogin()
        {
            LOGIN_PAGE = WorldServer.WEB_CONTENT_DIR + "realXtend_login.tpl";
            LOGIN_SUCCESS_PAGE = WorldServer.WEB_CONTENT_DIR + "rexloginsuccess.tpl";
        }

        /**
         *  Actual response content unknown at the moment, will make changes.
         */
        protected override void SendLoginSuccessTemplate(IHttpResponse response, Uri identity, Dictionary<Uri, OSD> attributes, UUID sessionID)
        {
            Dictionary<string, object> variables = new Dictionary<string, object>();
            variables["identity"] = identity;
            variables["information"] = server.HttpUri.ToString() + "login/" + sessionID.ToString() + "?" + attributes[AvatarAttributes.FIRST_NAME].AsString() + "&" + attributes[AvatarAttributes.LAST_NAME].AsString() + "&" + identity.ToString();

            try
            {
                string output = server.HttpTemplates.Render(LOGIN_SUCCESS_PAGE, variables);
                byte[] data = Encoding.UTF8.GetBytes(output);
                response.ContentLength = data.Length;
                response.ContentType = "text/html";
                response.Cookies.Add(new ResponseCookie("sessionID", sessionID.ToString(), DateTime.Now + TimeSpan.FromDays(1)));
                response.Body.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                Logger.Error("[OpenIDLogin] Failed to render " + LOGIN_SUCCESS_PAGE + " template: " + ex.Message);
            }
        }

        protected override ServiceCollection GetServices(Uri identity)
        {
            ServiceCollection services = base.GetServices(identity);

            //get avatar uri from xrd and add to services
            // Overriding CableBeachServices.FILESYSTEM_WEBDAV service if OpenID can offer one
            Service avatarservice = SimpleServices.CreateServiceFromLRDD(new Uri(identity.ToString() + ";xrd"), new Uri(CableBeachServices.FILESYSTEM_WEBDAV_AVATAR), true, true);
            if (avatarservice != null)
                services.Add(new Uri(CableBeachServices.FILESYSTEM_WEBDAV_AVATAR), avatarservice);

            return services;
        }
    }
}
